package com.trsj.lnsj.controller;

import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "微信支付接口")
@RestController
public class WeixinPayController {

//    private static final String DEFAULT_CLIENT_IP = "127.0.0.1";
//
//    private static final Logger LOGGER = LoggerFactory.getLogger(WeixinPayController.class);
//
//    private static final String WX_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//
//    // 根据实际情况填写 JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付
//    private static final String TRADE_TYPE_APP = "APP";
//
//    private static final String SUCCESS = "SUCCESS";
//
//    @Value("${pay.wx.merchantId}")
//    private String merchantId;
//
//    @Value("${pay.wx.appId}")
//    private String appId;
//
//    // 第二步拼接key，key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
//    @Value("${pay.wx.apikey}")
//    private String apiKey;
//
//    @Value("${pay.wx.notifyUrl}")
//    private String notifyUrl;
//
//    @Autowired
//    private PreOrderService preOrderService;
//
//    @Autowired
//    private PreOrderPayService preOrderPayService;
//
//    @Autowired
//    private ShoppingSpreeService shoppingSpreeService;
//
//    private static final Random random = new Random();
//
//    @GetMapping("/pay/wx/app/{orderId}")
//    @ApiImplicitParams({
//		@ApiImplicitParam(name = "orderId", paramType = "path", dataType = "String", value = "接口修正版本[可选]", required= true),
//		@ApiImplicitParam(name = Constants.VERSION_STRIKE_KEY, paramType = "header", dataType = "int", defaultValue = "0", value = "接口修正版本[可选]"),
//		@ApiImplicitParam(name = Constants.AUTH_TOKEN_KEY, paramType = "header", dataType = "string", required = true, value = "登录token[必填]"), })
//    @ApiResponses(value = { @ApiResponse(code = 400, message = "", response = ErrorResponse.class	) })
//    @ResponseBody
//    @Auth
//    public OrderPayFormDataResponse app(@PathVariable("orderId") String orderId) {
//    	 AppPreOrderQueryDTO order = preOrderService.findById(Long.valueOf(orderId));
//         if(order == null){
//             throw new BusinessException(BusinessErrors.INTENTION_ORDER_NOT_FOUND);
//         }
//         List<AppPreOrderGoodsDTO> appPreOrderGoodsList = order.getAppPreOrderGoodsList();
//         for(AppPreOrderGoodsDTO dto: appPreOrderGoodsList){
//         	if(dto.getSpreeId() != null && dto.getSpreeId() > 0 ){
//         		GoodsShoppingSpreeMapping mapping = shoppingSpreeService.findByGoodIdAndSpreeId(dto.getGoodsId(), dto.getSpreeId());
//         		if(mapping != null && mapping.getDepositStocks() != null && mapping.getDepositStocks() < dto.getQuantity()){
//                     throw new BusinessException(BusinessErrors.SYSTEM_ERROR);
//         		}
//         	}
//         }
//         if(order.getStatus() == OrderStatusEnum.PAID){
//             throw new BusinessException(BusinessErrors.INTENTION_ORDER_PAYED_STATUS_ERROR);
//         }
//         if(order.getStatus() == OrderStatusEnum.CANCELED || order.getStatus() == OrderStatusEnum.OVERDUE_CLOSED){
//             throw new BusinessException(BusinessErrors.INTENTION_ORDER_CANCEL_STATUS_ERROR);
//         }
//        String orderInfo = createOrderInfo(order, TRADE_TYPE_APP, notifyUrl);
//        WXOrderRespose resp = httpOrder(orderInfo);
//        // 根据微信文档return_code 和result_code都为SUCCESS的时候才会返回code_url
//        if (null != resp && SUCCESS.equals(resp.getReturn_code()) && SUCCESS.equals(resp.getResult_code())) {
//        	SortedMap<String, String> repData = new TreeMap<>();
//        	repData.put("appid", resp.getAppid());
//            repData.put("partnerid", resp.getMch_id());
//            repData.put("prepayid", resp.getPrepay_id());
//            repData.put("package", "Sign=WXPay");
//            repData.put("noncestr", UUID.randomUUID().toString().replaceAll("-", ""));
//            repData.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
//            String sign = WeixinUtil.sign(repData, apiKey); // 签名
//            repData.put("sign", sign);
//            return new OrderPayFormDataResponse(repData);
//        }
//        throw new BusinessException("调统一下单API失败");
//    }
//
////    @GetMapping(value = "/pay/wx/qrcode/{orderId}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
////    public void qrCode(@PathVariable("orderId") String orderId, HttpServletResponse response) {
////        String orderInfo = createOrderInfo(orderId, TRADE_TYPE_NATIVE, notifyUrl);
////        WXOrderRespose resp = httpOrder(orderInfo);
////        String codeUrl = null;
////        if (null != resp && SUCCESS.equals(resp.getReturn_code()) && SUCCESS.equals(resp.getResult_code())) {
////        	prDealOrder(resp,orderId);
////            codeUrl = resp.getCode_url();
////        } else {
////            throw new BusinessException("调统一下单API失败");
////        }
////
////        // 将返回预支付交易链接（code_url）生成二维码图片
////        try {
////            int width = 200;
////            int height = 200;
////            String format = "png";
////            Map<EncodeHintType, Object> hints = new HashMap<>();
////            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
////            BitMatrix bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, width, height, hints);
////            OutputStream out = null;
////            out = response.getOutputStream();
////            MatrixToImageWriter.writeToStream(bitMatrix, format, out);
////            out.flush();
////            out.close();
////        } catch (Exception e) {
////            LOGGER.error(e.getMessage(), e);
////        }
////
////    }
//
//    private String createOrderInfo(AppPreOrderQueryDTO order, String tradeType, String notifyUrl) {
//        WXOrderRequest req = buildOrderInfo(order, tradeType);
//        req.setSign(sign(req, apiKey));// 签名
//        // 将订单对象转为xml格式
//        XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));
//        xStream.alias("xml", WXOrderRequest.class);// 根元素名需要是xml
//        return xStream.toXML(req);
//    }
//
//    private WXOrderRequest buildOrderInfo(AppPreOrderQueryDTO order, String tradeType) {
//        WXOrderRequest req = new WXOrderRequest();
//        req.setAppid(appId);
//        req.setMch_id(merchantId);
//        req.setNonce_str(UUID.randomUUID().toString().replaceAll("-", ""));
//        String body = order.getAppPreOrderGoodsList().get(0).getProductName();
//        if(body != null && body.length() >= 128){
//        	body = body.substring(0, 127);
//        }
//        req.setBody(body);
//        String money = "";
//        if (HaveDeposit.YES.getValue().equals(order.getHaveDeposit())) {
//        	money = order.getTotalDeposit();
//        } else {
//        	money = order.getTotalSalePrice();
//        }
//        String busiSn= "xcmg" + DateUtils.formatDate(new Date()) + random.nextInt(10)+random.nextInt(10)+random.nextInt(10);
//        preOrderPayService.savePrePayInfo(order.getOrderId(), busiSn, money , PayMethodEnum.WECHATPAY.toString());
//        req.setOut_trade_no(busiSn);// 商户订单号
//        req.setTotal_fee(new BigDecimal(money).multiply(new BigDecimal(100)).longValue()+""); // 单位： 分, 1代表支付时是0.01元
//        req.setSpbill_create_ip(DEFAULT_CLIENT_IP);// 终端IP
//        req.setNotify_url(notifyUrl);// 通知地址, callback url
//        req.setTrade_type(tradeType);
//        req.setLimit_pay("no_credit");
//        return req;
//    }
//
//    private String sign(WXOrderRequest request, String apiKey) {
//        // 根据规则创建可排序的map集合
//        SortedMap<String, String> packageParams = new TreeMap<>();
//        packageParams.put("appid", request.getAppid());
//        packageParams.put("body", request.getBody());
//        packageParams.put("mch_id", request.getMch_id());
//        packageParams.put("nonce_str", request.getNonce_str());
//        packageParams.put("notify_url", request.getNotify_url());
//        packageParams.put("out_trade_no", request.getOut_trade_no());
//        packageParams.put("spbill_create_ip", request.getSpbill_create_ip());
//        packageParams.put("trade_type", request.getTrade_type());
//        packageParams.put("total_fee", request.getTotal_fee());
//        packageParams.put("limit_pay", request.getLimit_pay());
//        return WeixinUtil.sign(packageParams, apiKey);
//    }
//
//    private WXOrderRespose httpOrder(String orderInfo){
//    	XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));
//        // 将请求返回的内容通过xStream转换为UnifiedOrderRespose对象
//        xStream.alias("xml", WXOrderRespose.class);
//		try {
//			String WXOrderxml = WeixinUtil.postHttp (orderInfo,WX_URL);
//			Object object = xStream.fromXML(WXOrderxml);
//			WXOrderRespose response = new WXOrderRespose();
//			BeanUtils.copyProperties(object, response);
//			return response;
//		} catch (IOException e) {
//			LOGGER.error(e.getMessage(), e);
//		}
//		return null;
//    }
}
